"use strict";
class SerialController {
    constructor() {
        this.encoder = new TextEncoder();
        this.decoder = new TextDecoder();
        this.connected = false;
    }
    async init() {
        if ('serial' in navigator) {
            try {
                const port = await navigator.serial.requestPort();
                await port.open({ baudRate: 115200 });
                this.reader = port.readable.getReader();
                this.writer = port.writable.getWriter();
                this.connected = true;
                MixlyWebSerial.dataUpdate = setTimeout(MixlyWebSerial.dataRefresh, 20);
                //console.log(port);
            }
            catch (err) {
                console.error('There was an error opening the serial port:', err);
            }
        }
        else {
            console.error('Web serial doesn\'t seem to be enabled in your browser. Try enabling it by visiting:');
            console.error('chrome://flags/#enable-experimental-web-platform-features');
            console.error('opera://flags/#enable-experimental-web-platform-features');
            console.error('edge://flags/#enable-experimental-web-platform-features');
        }
    }
    async write(data) {
        if (this.connected) {
            const dataArrayBuffer = this.encoder.encode(data);
            return await this.writer.write(dataArrayBuffer);
        } else {
            return "disconnect";
        }
    }
    async writeArrayBuffer(data) {
        const dataArrayBuffer = data;
        var arrayBuffer = new Int8Array(dataArrayBuffer).buffer;
        return await this.writer.write(arrayBuffer);
    }
    async read() {
        if (this.connected) {
            try {
                const readerData = await this.reader.read();
                return this.decoder.decode(readerData.value);
            }
            catch (err) {
                const errorMessage = `error reading data: ${err}`;
                if (errorMessage.indexOf("The device has been lost") != -1) {
                    this.connected = false;
                } else {
                    console.error(errorMessage);
                }
                return errorMessage;
            }
        } else {
            return "disconnect";
        }
    }
}
const serialController = new SerialController();
